package ai;

import de.dqi.pong.engine.AI;
import de.dqi.pong.engine.Tick;
import static de.dqi.pong.engine.Direction.*;

/**
 * TODO Marius - finish class definition
 * <hr>
 * 
 * <hr><dl><dt>
 * Summary: </dt><br><dd>
 *  
 * </dd><br><dt>
 * Author: </dt><br><dd>
 *  dqi12thuermer
 * </dd></dl>
 */
public class Marius
		extends AI {
	
	private boolean	running;
	private long	currentTime;
	private long	lastTime;
	private long	deltaTime;
	private long	startTime;
	private double	x0;
	private double	y0;
	private double	y;
	private int		fps	= Tick.fps;
	private double	yNextBall;
	private double	deltas;
	private double	s;
	private double	v;
	private double	a;
	private double	t;
	private double	tpow;
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	
	private void move() {
		
		if (tick != null) {
			if (isLeft) {
				y = tick.posBatLeft;
			} else {
				y = tick.posBatRight;
			}
		}
		
		
		deltaTime = currentTime - lastTime;
		double x1 = tick.posBallX;
		double y1 = tick.posBallY;
		double deltaX = init.fieldWidth - (init.fieldWidth - x0) - (init.fieldWidth - x1);
		double deltaY = init.fieldWidth - (init.fieldWidth - y0) - (init.fieldWidth - y1);
		deltas = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
		v = (long) (2 * deltas / deltaTime);
		a = v / deltaTime;
		t = (v - 1) / a;
		tpow = Math.pow(t, 2);
		s = (a / 2) * tpow + 1 * Math.sqrt(tpow);
		yNextBall = (a / 2) * tpow + v + s;
		
		if (yNextBall <= 0 + init.ballRadius) {
			yNextBall = yNextBall + -2 * (yNextBall - 0 + init.ballRadius);
		}
		if (yNextBall >= init.fieldHeight - init.ballRadius) {
			yNextBall = yNextBall - 2 * (yNextBall - init.fieldHeight - init.ballRadius);
		}
		
		if (yNextBall > y + init.batSpan / 3) {
			direction = Up;
		} else if (yNextBall < y - init.batSpan / 3) {
			direction = Down;
		} else if (yNextBall == y - init.batSpan / 3) {
			direction = Hold;
		}
		
	}
	
	@Override
	public void run() {
		running = true;
		int counter = 0;
		while (running) {
			currentTime = System.currentTimeMillis();
			
			if (counter == 1) {
				move();
			}
			counter = 1;
			try {
				long timeout = (1000 / fps) - (System.currentTimeMillis() - currentTime);
				if (timeout > 0) {
					Thread.sleep(timeout);
				}
			} catch (InterruptedException e) {
				System.err.println("Wait interval interrupted");
			}
			lastTime = currentTime;
			x0 = tick.posBallX;
			y0 = tick.posBallY;
			
		}
	}
}
